<template>
	<view class="container">
		<!-- 购物车列表 -->
		<view class="cart-list" v-if="cartList.length > 0">
			<view class="cart-item" v-for="item in cartList" :key="item.id">
				<view class="goods-info">
					<image 
						class="goods-img" 
						:src="getGoodsImage(item.goodsImage)" 
						mode="aspectFill"
					></image>
					<view class="info">
						<view class="title">{{item.goodsTitle}}</view>
						<view class="price">￥{{item.goodsPrice}}</view>
						<view class="gift-rules" v-if="item.giftRuleText">
							<text class="tag">赠</text>
							<text class="rule-text">{{item.giftRuleText}}</text>
						</view>
					</view>
					<view class="delete" @click="deleteItem(item)">
						<uni-icons type="trash" size="20" color="#999"></uni-icons>
					</view>
				</view>
				
				<view class="order-info">
					<view class="num-section">
						<text>购买数量：</text>
						<view class="num-display">{{item.num}}件</view>
					</view>
					
					<!-- 赠送信息 -->
					<view class="gift-info" v-if="item.giftNum > 0">
						<text class="tag">赠</text>
						<text class="gift-text">赠送{{item.giftNum}}件</text>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty" v-else>
			<image src="/static/images/empty-goods.png" mode="aspectFit"></image>
			<text>购物车空空如也</text>
			<button class="go-shopping" @click="goShopping">去逛逛</button>
		</view>

		<!-- 底部结算栏 -->
		<view class="footer" v-if="cartList.length > 0">
			<view class="total-info">
				<view class="price-info">
					<text>合计：</text>
					<text class="price">￥{{totalPrice}}</text>
				</view>
				<view class="num-info">
					<text>下单{{totalOrderNum}}件</text>
					<text class="gift" v-if="totalGiftNum > 0">赠送{{totalGiftNum}}件</text>
					<text class="total">共{{totalNum}}件</text>
				</view>
			</view>
			<button class="checkout-btn" @click="checkout">结算</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onShow,onLoad } from '@dcloudio/uni-app'
import { config } from '@/utils/config.js'

// ��列表
const cartList = ref([])

// 检查登录状态
const checkLogin = () => {
	const token = uni.getStorageSync('token')
	if (!token) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		// 跳转到登录页
		setTimeout(() => {
			uni.navigateTo({
				url: '/pages/user/login'
			})
		}, 1500)
		return false
	}
	return true
}

// 计算总价和总数量
const totalPrice = computed(() => {
	return cartList.value.reduce((total, item) => {
		return total + item.goodsPrice * item.num
	}, 0).toFixed(2)
})

const totalOrderNum = computed(() => {
	return cartList.value.reduce((total, item) => total + item.num, 0)
})

const totalGiftNum = computed(() => {
	return cartList.value.reduce((total, item) => total + (item.giftNum || 0), 0)
})

const totalNum = computed(() => {
	return totalOrderNum.value + totalGiftNum.value
})

// 添加 onLoad 生命周期
onLoad(() => {
	getCartList()
})

// 修改 onShow 生命周期，添加登录状态检查
onShow(() => {
	const token = uni.getStorageSync('token')
	if (token) {
		getCartList()
	} else {
		cartList.value = []
	}
})

// 修改获取购物车列表方法，添加加载状态
const loading = ref(false)

const getCartList = async () => {
	if (!checkLogin() || loading.value) return
	
	loading.value = true
	try {
		const res = await uni.request({
			url: config.baseUrl + '/api/cart/list',
			method: 'GET',
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`
			}
		})

		if (res.data.code === 200) {
			const cartData = res.data.data
			if (!cartData || !cartData.list) {
				cartList.value = []
				return
			}
			cartList.value = cartData.list
		} else {
			throw new Error(res.data.message || '获取购物车列表失败')
		}
	} catch (error) {
		console.error('获取购物车列表失败:', error)
		uni.showToast({
			title: error.message || '获取购物车列表失败',
			icon: 'none'
		})
		cartList.value = []
	} finally {
		loading.value = false
	}
}

// 获取商品图片
const getGoodsImage = (image) => {
	if (!image) return '/static/images/logo.png'
	return image.startsWith('http') ? image : config.baseUrl + image
}

// 更新商品数量
const updateNum = async (item, delta) => {
	if (!checkLogin()) return
	
	const newNum = item.num + delta
	if (newNum < 1) return
	
	try {
		const res = await uni.request({
			url: config.baseUrl + `/api/cart/${item.id}/num`,
			method: 'PUT',
			data: {
				num: newNum
			},
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`,
				'Content-Type': 'application/json'
			}
		})

		if (res.data.code === 200) {
			item.num = newNum
			// 重新获取列表以更新赠送数量
			getCartList()
		} else {
			throw new Error(res.data.message)
		}
	} catch (error) {
		console.error('更新数量失败:', error)
		uni.showToast({
			title: '更新数量失败',
			icon: 'none'
		})
	}
}

// 处理数量输入
const onNumInput = (item) => {
	// 移除非数字字符
	item.num = item.num.toString().replace(/[^\d]/g, '')
	if (item.num === '') item.num = '1'
	
	// 转换为数字并限制范围
	let num = parseInt(item.num)
	if (num > item.goodsStock) {
		num = item.goodsStock
		uni.showToast({
			title: '超出库存数量',
			icon: 'none'
		})
	}
	item.num = num
	
	// 延迟更新，避免频繁请求
	clearTimeout(item._timer)
	item._timer = setTimeout(() => {
		updateNum(item, 0)
	}, 500)
}

// 检查数量输入
const checkNum = (item) => {
	let num = parseInt(item.num)
	if (isNaN(num) || num < 1) {
		num = 1
	}
	if (num > item.goodsStock) {
		num = item.goodsStock
		uni.showToast({
			title: '超出库存数量',
			icon: 'none'
		})
	}
	item.num = num
	updateNum(item, 0)
}

// 删除商品
const deleteItem = (item) => {
	if (!checkLogin()) return
	
	uni.showModal({
		title: '提示',
		content: '确定要删除该商品吗？',
		success: async (res) => {
			if (res.confirm) {
				try {
					const result = await uni.request({
						url: config.baseUrl + `/api/cart/${item.id}`,
						method: 'DELETE',
						header: {
							'Authorization': `Bearer ${uni.getStorageSync('token')}`
						}
					})

					if (result.data.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						})
						getCartList()
					} else {
						throw new Error(result.data.message)
					}
				} catch (error) {
					console.error('删除失败:', error)
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					})
				}
			}
		}
	})
}

// 结算
const checkout = async () => {
	if (!checkLogin()) return
	
	try {
		uni.showLoading({
			title: '正在结算...'
		})
		
		const res = await uni.request({
			url: config.baseUrl + '/api/cart/checkout',
			method: 'POST',
			header: {
				'Authorization': `Bearer ${uni.getStorageSync('token')}`,
				'Content-Type': 'application/json'
			}
		})
		
		uni.hideLoading()
		
		if (res.data.code === 200) {
			// 清空购物车数据
			getCartList()
			
			uni.showToast({
				title: '下单成功',
				icon: 'success',
				success: () => {
					setTimeout(() => {
						// 跳转到订单列表
						uni.navigateTo({
							url: '/pages/order/list'
						})
					}, 1500)
				}
			})
		} else {
			// 处理特定错误情况
			if (res.data.code === 400) {
				if (res.data.message.includes('地址')) {
					uni.showModal({
						title: '提示',
						content: '请先添加收货地址',
						confirmText: '去添加',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/address/list'
								})
							}
						}
					})
					return
				}
				if (res.data.message.includes('购物车')) {
					uni.showToast({
						title: '购物车为空',
						icon: 'none'
					})
					return
				}
			}
			throw new Error(res.data.message || '下单失败')
		}
	} catch (error) {
		uni.hideLoading()
		console.error('下单失败:', error)
		uni.showToast({
			title: error.message || '下单失败',
			icon: 'none'
		})
	}
}

// 跳转到首页
const goShopping = () => {
	uni.switchTab({
		url: '/pages/index/index'
	})
}
</script>

<style lang="scss">
.container {
	min-height: 100vh;
	background: #f7f8fa;
	padding-bottom: 120rpx;
}

.cart-list {
	padding: 20rpx;
	
	.cart-item {
		background: #fff;
		border-radius: 12rpx;
		padding: 30rpx;
		margin-bottom: 20rpx;
		
		.goods-info {
			display: flex;
			align-items: flex-start;
			margin-bottom: 30rpx;
			
			.goods-img {
				width: 160rpx;
				height: 160rpx;
				border-radius: 8rpx;
				margin-right: 20rpx;
				flex-shrink: 0;
			}
			
			.info {
				flex: 1;
				margin-right: 20rpx;
				
				.title {
					font-size: 28rpx;
					color: #333;
					font-weight: bold;
					margin-bottom: 16rpx;
					line-height: 1.4;
				}
				
				.price {
					font-size: 32rpx;
					color: #ff6b81;
					font-weight: bold;
					margin-bottom: 16rpx;
				}
				
				.gift-rules {
					display: flex;
					align-items: center;
					margin-top: 8rpx;
					
					.tag {
						background: #ff6b81;
						color: #fff;
						font-size: 20rpx;
						padding: 4rpx 8rpx;
						border-radius: 4rpx;
						margin-right: 8rpx;
					}
					
					.rule-text {
						font-size: 24rpx;
						color: #ff6b81;
					}
				}
			}
			
			.delete {
				padding: 10rpx;
				
				&:active {
					opacity: 0.7;
				}
			}
		}
		
		.order-info {
			background: #f8f9fa;
			border-radius: 12rpx;
			padding: 20rpx;
			
			.num-section {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin-bottom: 16rpx;
				
				text {
					font-size: 28rpx;
					color: #666;
				}
				
				.num-display {
					font-size: 28rpx;
					color: #333;
					font-weight: bold;
				}
			}
			
			.gift-info {
				display: flex;
				align-items: center;
				
				.tag {
					background: #ff6b81;
					color: #fff;
					font-size: 20rpx;
					padding: 4rpx 8rpx;
					border-radius: 4rpx;
					margin-right: 8rpx;
				}
				
				.gift-text {
					font-size: 24rpx;
					color: #ff6b81;
				}
			}
		}
	}
}

.empty {
	padding-top: 200rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	
	image {
		width: 240rpx;
		height: 240rpx;
		margin-bottom: 30rpx;
	}
	
	text {
		font-size: 28rpx;
		color: #999;
		margin-bottom: 40rpx;
	}
	
	.go-shopping {
		width: 240rpx;
		height: 80rpx;
		background: #ff6b81;
		color: #fff;
		border-radius: 40rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
}

.footer {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	height: 100rpx;
	background: #fff;
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0,0,0,0.05);
	
	.total-info {
		flex: 1;
		
		.price-info {
			font-size: 28rpx;
			color: #333;
			margin-bottom: 8rpx;
			
			.price {
				font-size: 36rpx;
				color: #ff6b81;
				font-weight: bold;
			}
		}
		
		.num-info {
			display: flex;
			align-items: center;
			font-size: 24rpx;
			color: #666;
			
			.gift {
				color: #ff6b81;
				margin: 0 8rpx;
			}
			
			.total {
				color: #333;
				font-weight: bold;
			}
		}
	}
	
	.checkout-btn {
		width: 200rpx;
		height: 72rpx;
		background: #ff6b81;
		color: #fff;
		border-radius: 36rpx;
		font-size: 28rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0;
		
		&:active {
			background: darken(#ff6b81, 5%);
		}
	}
}
</style> 